import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel,QGridLayout , QHBoxLayout
from PyQt5.QtGui import QColor, QPalette
from PyQt5.QtCore import Qt

class ColorPaletteApp(QWidget):
    def __init__(self):
        super().__init__()
        self.colors = [
            QColor(255, 0, 0),      # 红色
            QColor(0, 255, 0),      # 绿色  
            QColor(0, 0, 255),      # 蓝色
            QColor(255, 255, 0),    # 黄色
            QColor(255, 0, 255),    # 洋红
            QColor(0, 255, 255),    # 青色
        ]
        self.init_ui()
        
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 调色板显示
        self.palette_layout = QGridLayout()
        self.update_palette_display()
        
        # 控制按钮
        btn_layout = QHBoxLayout()
        add_btn = QPushButton('添加颜色')
        clear_btn = QPushButton('清空调色板')
        
        add_btn.clicked.connect(self.add_color)
        clear_btn.clicked.connect(self.clear_palette)
        
        btn_layout.addWidget(add_btn)
        btn_layout.addWidget(clear_btn)
        
        layout.addLayout(self.palette_layout)
        layout.addLayout(btn_layout)
        
        self.setLayout(layout)
        self.setWindowTitle('简易调色板')
        
    def update_palette_display(self):
        """更新调色板显示"""
        # 清除现有显示
        for i in reversed(range(self.palette_layout.count())):
            self.palette_layout.itemAt(i).widget().setParent(None)
            
        # 添加颜色块
        for i, color in enumerate(self.colors):
            color_btn = QPushButton()
            color_btn.setFixedSize(60, 60)
            color_btn.setStyleSheet(f"background-color: {color.name()}; border: 1px solid black;")
            color_btn.clicked.connect(lambda checked, idx=i: self.edit_color(idx))
            
            row = i // 3
            col = i % 3
            self.palette_layout.addWidget(color_btn, row, col)
            
    def add_color(self):
        """添加新颜色到调色板"""
        from PyQt5.QtWidgets import QColorDialog
        
        color = QColorDialog.getColor(
            parent=self,
            title="选择要添加的颜色"
        )
        
        if color.isValid():
            self.colors.append(color)
            self.update_palette_display()
            
    def edit_color(self, index):
        """编辑指定位置的颜色"""
        from PyQt5.QtWidgets import QColorDialog
        
        color = QColorDialog.getColor(
            initial=self.colors[index],
            parent=self,
            title="编辑颜色",
            options=QColorDialog.ShowAlphaChannel
        )
        
        if color.isValid():
            self.colors[index] = color
            self.update_palette_display()
            
    def clear_palette(self):
        """清空调色板"""
        self.colors.clear()
        self.update_palette_display()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ColorPaletteApp()
    window.show()
    sys.exit(app.exec_())
